import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'function.dart';
import 'dart:io';
import 'package:flutter_qq/flutter_qq.dart';

class AccountPage extends StatefulWidget {
  AccountPage(this.mainColor);
  final mainColor;
  @override
  _AccountPageState createState() => new _AccountPageState();
}

class _AccountPageState extends State<AccountPage> {
  bool qqOn = false;
  bool accountOn = false;
  String account = "";
  String password = "";
  String uid = "";
  bool logout = false;
  @override
  void initState() {
    initUser();
    super.initState();
  }

  Future<bool> willPop() {
    print(this.logout);
    Navigator.of(context).pop(this.logout);
    return new Future.value(false);
  }

  initUser() async {
    this.uid = await getStorage("uid");
    if (this.uid != null) {
      var info = await getUserInfo(this.uid);
      if (info == null) {
        return false;
      }
      if (info['code'] == 1) {
        qqOn = info['msg']['bindqq'] != "";
        accountOn = info['msg']['username'] != '';
        setState(() {});
      }
    }
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return new WillPopScope(
        child: Scaffold(
          appBar: new CupertinoNavigationBar(
            actionsForegroundColor: Colors.white,
            backgroundColor: widget.mainColor,
            middle: new Text(
              "账号设置",
              style: new TextStyle(
                color: Colors.white,
                fontWeight: FontWeight.normal,
              ),
            ),
          ),
          body: new Container(
            child: new Column(
              children: <Widget>[
                new ListTile(
                  leading: new ImageIcon(AssetImage("images/qq.png")),
                  title: new Text("绑定QQ"),
                  trailing: CupertinoSwitch(
                    value: qqOn,
                    onChanged: (val) async {
                      if (val) {
                        if (Platform.isIOS) {
                          FlutterQq.registerQQ("101218757");
                        } else {
                          FlutterQq.registerQQ("101475558");
                        }

                        var qqResult = await FlutterQq.login();
                        if (qqResult.code == 0) {
                          var qqInfo = await getQQInfo(
                            qqResult.response['accessToken'],
                            qqResult.response['openid'],
                          );
                          var bindRes = await bindQQ(uid, qqResult.response['openid'], qqInfo['nickname'], qqInfo['figureurl_qq_2']);
                          if (bindRes['code'] == 0) {
                            toast(bindRes['msg']);
                          } else {
                            toast("绑定成功");
                            qqOn = val;
                            initUser();
                          }
                        } else if (qqResult.code == 1) {
                          toast("登录失败");
                        } else {
                          toast("取消登录");
                        }
                      } else {
                        if (accountOn == false) {
                          toast("请至少保留一种登录方式");
                        }
                        showDialog(
                          context: context,
                          builder: (BuildContext context) {
                            return AlertDialog(
                              title: const Text('解绑QQ'),
                              content: new Text("解绑QQ后将无法使用QQ登录"),
                              actions: <Widget>[
                                FlatButton(
                                  child: Text(
                                    '解绑',
                                    style: new TextStyle(fontWeight: FontWeight.bold, color: Colors.red),
                                  ),
                                  onPressed: () async {
                                    var unBindRes = await unBindQQ(uid);
                                    if (unBindRes['code'] == 0) {
                                      toast(unBindRes['msg']);
                                    } else {
                                      toast("解绑成功");
                                      qqOn = val;
                                      initUser();

                                      Navigator.of(context).pop();
                                    }
                                  },
                                ),
                                FlatButton(
                                  child: Text('取消'),
                                  onPressed: () {
                                    Navigator.of(context).pop();
                                  },
                                ),
                              ],
                            );
                          },
                        );
                      }
                    },
                  ),
                ),
                new Divider(
                  height: 1.0,
                ),
                new ListTile(
                  leading: new Icon(Icons.account_circle),
                  title: new Text("账号密码"),
                  trailing: CupertinoSwitch(
                    value: accountOn,
                    onChanged: (val) async {
                      if (val) {
                        showDialog(
                          context: context,
                          builder: (BuildContext context) {
                            return AlertDialog(
                              title: const Text('绑定账号密码'),
                              content: new Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                mainAxisSize: MainAxisSize.min,
                                children: <Widget>[
                                  new Text(
                                    "无法绑定已存在的账号，将注册新账号以绑定",
                                    style: TextStyle(color: Colors.red),
                                  ),
                                  new TextField(
                                    onChanged: (val) => account = val,
                                    style: new TextStyle(fontSize: 15.0, color: Colors.black),
                                    decoration: new InputDecoration(
                                      hintText: "请输入账号",
                                      labelText: "账号",
                                      labelStyle: TextStyle(
                                        fontWeight: FontWeight.w700,
                                      ),
                                    ),
                                  ),
                                  new TextField(
                                    onChanged: (value) {
                                      password = value;
                                    },
                                    style: new TextStyle(
                                      fontSize: 15.0,
                                      color: Colors.black,
                                    ),
                                    decoration: new InputDecoration(
                                      hintText: "请输入密码",
                                      labelText: "密码",
                                      labelStyle: TextStyle(
                                        fontWeight: FontWeight.w700,
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                              actions: <Widget>[
                                FlatButton(
                                  child: Text(
                                    '注册并绑定',
                                  ),
                                  onPressed: () async {
                                    if (account == "") {
                                      toast("请输入用户名");
                                      return;
                                    }
                                    if (password == "") {
                                      toast("请输入密码");
                                      return;
                                    }
                                    var bindRes = await bindAccount(uid, account, password);
                                    if (bindRes['code'] == 0) {
                                      toast(bindRes['msg']);
                                    } else {
                                      toast("绑定成功");
                                      accountOn = val;
                                      account = "";
                                      password = "";
                                      initUser();

                                      Navigator.of(context).pop();
                                    }
                                  },
                                ),
                                FlatButton(
                                  child: Text('取消'),
                                  onPressed: () {
                                    account = "";
                                    password = "";
                                    Navigator.of(context).pop();
                                  },
                                ),
                              ],
                            );
                          },
                        );
                      } else {
                        showDialog(
                          context: context,
                          builder: (BuildContext context) {
                            return AlertDialog(
                              title: const Text('绑定账号密码'),
                              content: new Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                mainAxisSize: MainAxisSize.min,
                                children: <Widget>[
                                  new Text(
                                    "解绑账号后，原账号密码将被注销",
                                    style: TextStyle(color: Colors.red),
                                  ),
                                ],
                              ),
                              actions: <Widget>[
                                FlatButton(
                                  child: Text(
                                    '解绑并注销',
                                    style: TextStyle(color: Colors.red),
                                  ),
                                  onPressed: () async {
                                    var unBindRes = await unBindAccount(uid);
                                    if (unBindRes['code'] == 0) {
                                      toast(unBindRes['msg']);
                                    } else {
                                      toast("解绑成功");
                                      accountOn = val;
                                      initUser();

                                      Navigator.of(context).pop();
                                    }
                                  },
                                ),
                                FlatButton(
                                  child: Text('取消'),
                                  onPressed: () {
                                    Navigator.of(context).pop();
                                  },
                                ),
                              ],
                            );
                          },
                        );
                      }

                      setState(() {});
                    },
                  ),
                ),
                new Divider(
                  height: 1.0,
                ),
                new ListTile(
                  leading: new Icon(Icons.exit_to_app),
                  title: new Text("注销登录"),
                  trailing: new Icon(Icons.chevron_right),
                  onTap: () {
                    showDialog(
                      context: context,
                      builder: (BuildContext context) {
                        return AlertDialog(
                          title: const Text('注销登录'),
                          actions: <Widget>[
                            FlatButton(
                              child: Text(
                                '注销',
                                style: new TextStyle(fontWeight: FontWeight.bold, color: Colors.red),
                              ),
                              onPressed: () {
                                removeStorage("uid");
                                toast("注销成功");
                                this.logout = true;
                                setState(() {});
                                Navigator.of(context).pop();
                              },
                            ),
                            FlatButton(
                              child: Text('取消'),
                              onPressed: () {
                                Navigator.of(context).pop();
                              },
                            ),
                          ],
                        );
                      },
                    );
                  },
                ),
                new Divider(
                  height: 1.0,
                ),
              ],
            ),
          ),
        ),
        onWillPop: willPop);
  }
}
